package com.shujia.flink.sql


import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo4ReadMysql {
  def main(args: Array[String]): Unit = {
    //flink  流处理的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置flink  sql 配置
    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() // 使用blink 的计划器（解析sql）
      .inStreamingMode()
      .build()

    //创建table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)

    /**
      * jdbc:如果作为source，因为数据是有界的所以是有界流
      *
      *
      * 注意事项：
      * flink表中的数据必须与需要读取的mysql中的表结构一致
      */


    bsTableEnv.executeSql(
      """
        |CREATE TABLE mysql_student (
        |  id INT,
        |  name STRING,
        |  age INT,
        |  sex  STRING,
        |  clazz STRING,
        |  PRIMARY KEY (id) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/student',
        |   'table-name' = 'students',
        |   'username'='root',
        |   'password'='123456'
        |)
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table(
        |id INT,
        |name STRING,
        |age INT,
        |sex  STRING,
        |clazz STRING
        |)
        |WITH ('connector' = 'print')
      """.stripMargin)

    bsTableEnv.executeSql(
      """
        |insert into print_table
        |select * from mysql_student
      """.stripMargin)
  }
}
